//
//  HeadTitleView.swift
//  Yun
//
//  Created by 新宝 on 2017/9/20.
//  Copyright © 2017年 新宝. All rights reserved.
//

import UIKit
//class代表该协议只能被类遵循
protocol HeadTitleViewDelegate:class{
    func titleView(_ titleView:HeadTitleView,index: Int)
}

class HeadTitleView: UIView {
    
    weak var headTitleDelegate:HeadTitleViewDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    //必须实现的必要构造器
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //scrollView懒加载
       lazy var titleScrollView:UIScrollView={
        let titleScrollView=UIScrollView()
        titleScrollView.frame=CGRect(x:0,y:20,width:screenWidth,height:40)
        titleScrollView.showsHorizontalScrollIndicator=false
        titleScrollView.alwaysBounceHorizontal=true
        titleScrollView.scrollsToTop=false
        return titleScrollView
    }()
    /// 标题数组
    fileprivate lazy var titleLabels = [TitleLabel]()
    fileprivate lazy var currentIndex:Int=0
    
    //水平划线
    lazy var lineView:UIView={
        let lineView=UIView()
        lineView.frame=CGRect(x:15,y:36,width:30,height:2)
        lineView.backgroundColor=UIColor.red
        return lineView
    }()
    //文字数组
    lazy var  titleArray:NSArray={
        var titleArray=NSArray()
        titleArray=["体育新闻","头条","财经","娱乐圈","军事","历史问题","科技"]
        return titleArray
    }()
    
    fileprivate class TitleLabel:UILabel{
        /// 用来记录当前 label 的缩放比例
        var currentScale: CGFloat = 1.0 {
            didSet {
                self.transform = CGAffineTransform(scaleX: currentScale, y: currentScale)
            }
        }
    }

    override var frame: CGRect{
        didSet{
            let newFrame=CGRect(x:0,y:0,width:self.frame.size.width,height:64)
            super.frame=newFrame
        }
    }
    
}



//以下为类的扩展部分------------------------------------------------------------------------
extension HeadTitleView{
    
    fileprivate func setupUI(){
        self.backgroundColor=UIColor.white
        self.addSubview(titleScrollView)
        titleScrollView.addSubview(lineView)
        self.setupTitleLabel()
        
}
    
    fileprivate func setupTitleLabel(){
        for i in 0...6{
            let label=TitleLabel()
            label.text=titleArray[i] as? String
            label.tag=i
            label.textAlignment = .center
            label.textColor=label.tag==0 ? UIColor.red:UIColor.black
            self.titleScrollView.addSubview(label)
            titleLabels.append(label)
            //给每个Label添加手势
            let tapGes=UITapGestureRecognizer(target:self,action:#selector(titleLabelClick(_:)))
           label.addGestureRecognizer(tapGes)
            label.isUserInteractionEnabled=true
        }
        self.creatTitleLabelFrame()
    }
    
    //为Label设置Frame
    fileprivate func creatTitleLabelFrame(){
        for i in 0...6{
            var w:CGFloat=0
            let h:CGFloat=40
            var x:CGFloat=0
            let y:CGFloat=0
            let label=titleLabels[i] as TitleLabel
            let titleStrig=titleLabels[i].text as NSString?
            w=(titleStrig?.boundingRect(with: CGSize(width:CGFloat(MAXFLOAT),height:0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:label.font], context: nil).width)!
            
            if i == 0{
                x=15
                self.lineView.frame.size.width=w
                self.lineView.frame.origin.x=x
            }else{
               let preLabel=titleLabels[i-1]
               x=preLabel.frame.maxX+15
                
            }
            label.frame=CGRect(x:x,y:y,width:w,height:h)
        }
        self.titleScrollView.contentSize=CGSize(width:titleLabels.last!.frame.maxX+20,height:0)
    }

}


extension HeadTitleView{
    
     @objc fileprivate func titleLabelClick(_ tapGes:UITapGestureRecognizer){
        //取出用户点击的View
        let targetLabel=tapGes.view as! TitleLabel
        
        //改变选中文字大小
        self.changeTitleLabel(targetLabel.tag)
        
        //调整下划线的位置
        UIView.animate(withDuration: 0.1) {
            self.lineView.frame.size.width=targetLabel.frame.size.width
            self.lineView.frame.origin.x=targetLabel.frame.origin.x
        }
        
        //通知代理
        headTitleDelegate?.titleView(self, index: targetLabel.tag)
        
    }
    
    fileprivate func changeTitleLabel(_ targetIndex:Int){
        //如果选中已经选中的，那么什么也不做
        if targetIndex==currentIndex{return}
        
        //取出选中的
        let targetLabel=titleLabels[targetIndex]
        let currentLabel=titleLabels[currentIndex]
        
        //调整下划线的位置
        UIView.animate(withDuration: 0.1) {
            self.lineView.frame.size.width=targetLabel.frame.size.width
            self.lineView.frame.origin.x=targetLabel.frame.origin.x
        }

        //设置颜色
        targetLabel.textColor=UIColor.red
        currentLabel.textColor=UIColor.black
        //把选中的字体放大
        targetLabel.currentScale=1.1
        //把上次选中的还原
        currentLabel.currentScale=1.0
        //记录Label下标值
        currentIndex=targetIndex
        
        // 调整偏移
        var offsetX=targetLabel.center.x-screenWidth*0.5
        if offsetX<0{
            offsetX=0
        }
        
        //最大偏移量
        let maxOffsetX = titleLabels.last!.frame.maxX+20-screenWidth
        if offsetX > maxOffsetX{
            offsetX=maxOffsetX
        }
        
        titleScrollView.setContentOffset(CGPoint(x:offsetX,y:0), animated: true)
    }
    
}

extension HeadTitleView:NewsViewDelegate{
    func newsView(_ controller: NewsViewController, currentIndex: Int) {
       self.changeTitleLabel(currentIndex)
    }
}


